<template>
  <!-- /imgs/activities/material/bedroom/1.png 全局搜索后注意替换 -->
  <div class="group_photo">
    <van-nav-bar class="navBar" style="" title="" left-text="" left-arrow @click-left="back" />
    <div class="">
      <div class="right_info">
        <div class="address landscape flex flex-justify-left flex-items-center">
          <img src="https://jwc-static.jdwxk.com/imgs/map/position_icon.png" alt="">
          <span>{{ state.position.name }}</span>
        </div>
        <div class="landscape user flex flex-justify-center flex-items-center">
          <div class="avatar">
            <img src="https://jwc-static.jdwxk.com/imgs/map/head_man.png" alt="">
          </div>
          <div class="name">
            {{ userInfo.name }}
          </div>
        </div>
      </div>
      <div class="background_box decorations">
        <div class="background_content" />
      </div>
      <div class="background_box main_view" @click="cancelActived">
        <div ref="targetAreaRef" class="background_content target_area" :style="backgroundState.eleStyle">
          <!-- <div v-for="(scene, sceneIndex) in backgroundState.options" :key="sceneIndex" class="scene_bg" v-show="backgroundState.current-1 == sceneIndex">
            <img :src="cardBaseUrl + scene" alt="">
          </div> -->
          <div id="target_item" class="target_item">
            <div
              v-for="element in materailState.target" :id="`material_img_${element.id}`" :key="element.id"
              class="material_img" :class="{ material_img_actived: element.id === materailState.activedId }" alt=""
              style="transform: translate(150px,350px);" @click.stop="setActived(element.id)"
            >
              <!-- <img :src="element.img" alt=""> -->
              <img class="card_img" :src="cardBaseUrl + element.pic1" alt="">
              <div v-if="element.id === materailState.activedId" class="close" @click="deleteCard(element.id)">
                <img src="https://jwc-static.jdwxk.com/imgs/activities/materail_delete_icon.png" alt="">
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="toggle_bg">
        <img src="https://jwc-static.jdwxk.com/imgs/activities/materail_last_icon.png" alt="" class="last_img" @click="toggleBg(-1)">
        <div class="current">
          {{ backgroundState.current }}/{{ backgroundState.options.length }}
        </div>
        <img src="https://jwc-static.jdwxk.com/imgs/activities/materail_next_icon.png" alt="" class="next_img" @click="toggleBg(+1)">
      </div>

      <div class="landscape hover_btns">
        <div class="btn1 btn" @click="OpenMaterailPop">
          <img src="https://jwc-static.jdwxk.com/imgs/activities/materail_open_icon.png" alt="" srcset="">
          <span>集卡册</span>
        </div>
        <div class="btn btn2" @click="saveAsImage">
          <img src="https://jwc-static.jdwxk.com/imgs/activities/materail_save_icon.png" alt="" srcset="">
          <span>保存</span>
        </div>
      </div>

      <div class="materail_pop">
        <van-popup v-model:show="visible" round class="" @close="closePop">
          <div v-if="materailState.source" class="materail_pop_box flex flex-items-center">
            <div class="cards">
              <div
                v-for="(card, cardIndex) in materailState.source" :key="cardIndex" class="card"
                @click="addCard(card)"
              >
                <div class="landscape card_title">
                  <img src="https://jwc-static.jdwxk.com/imgs/map/card_title_bg.png" alt="">
                  <span>{{ card.name }}</span>
                </div>
                <div class="source_area">
                  <img class="card_img" :src="cardBaseUrl + card.pic1" alt="">
                </div>
              </div>
            </div>
            <div class="landscape title">
              <img src="https://jwc-static.jdwxk.com/imgs/map/cards_head_icon.png" alt="">
            </div>
            <div class="landscape close flex flex-justify-center flex-items-center" @click="closePop">
              <img src="https://jwc-static.jdwxk.com/imgs/map/close.png" alt="">
            </div>
            <div class="landscape tip">
              <!-- AR扫码标志性物品会有惊喜哦～ -->
              点击卡片可以添加到场景(同一卡片只能添加一次)
            </div>
          </div>
        </van-popup>
      </div>

      <div class="materail_pop">
        <van-popup id="saveImgPop" v-model:show="saveImgVisible" round :lazy-render="false" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, reactive, ref } from 'vue'

import { useRouter } from 'vue-router'
import html2canvas from 'html2canvas'
import Hammer from 'hammerjs'

import { getAllCards, getSceneBg } from '@/api/activities'

import { useUserStoreWidthOut } from '@/store/modules/user'

const cardBaseUrl = ref(import.meta.env.VITE_GLOB_IMG_URL)
const userStore = useUserStoreWidthOut()
const userInfo = computed(() => userStore.getUserInfo)

const router = useRouter()
function back() {
  router.back()
}

const state = reactive({
  position: {
    name: '景坞村',
  },
  // user: {
  //   sex: 1,
  //   name: '李云龙',
  //   points: 60,
  // },
})

const materailState = reactive({
  source: null,
  target: [],
  hammerManages: [],
  activedId: '',
})
const backgroundState = reactive({
  options: [],
  eleStyle: {},
  current: 1,
})
const visible = ref(false)
const saveImgVisible = ref(false)

const targetAreaRef = ref(null)
async function saveAsImage() {
  try {
    const canvas = await html2canvas(targetAreaRef.value, {
      // scrollY: 0,
      // scrollY: -500,
      useCORS: true, // 【重要】开启跨域配置
    })
    const img = canvas.toDataURL('image/png')

    const a = document.createElement('a')
    a.href = img
    a.download = 'groupPhoto.png'
    // a.click()

    const DOM = document.getElementById('saveImgPop')
    const imgDOM = document.createElement('img')
    imgDOM.src = img
    imgDOM.style = ''
    imgDOM.crossOrigin = 'anonymous'
    const boxDOM = document.createElement('div')
    boxDOM.appendChild(imgDOM)

    const ua = navigator.userAgent.toLowerCase()
    // if (ua.match(/MicroMessenger/i) === 'micromessenger') {
    if (/micromessenger/.test(ua)) {
      console.log('微信环境--ua：', ua)
      DOM.innerHTML = '<span id="tip2"></span>'
      DOM.appendChild(boxDOM)
      saveImgVisible.value = true
    }
    else {
      console.log('非微信环境==ua：', ua)
      a.click()
      // DOM.innerHTML = ""
      // DOM.appendChild(boxDOM)
      // saveImgVisible.value = true
    }
  }
  catch (error) {
    console.error('Error capturing element:', error)
  }

  // const element = targetAreaRef.value;
  // const canvas = document.createElement('canvas');
  // const ctx = canvas.getContext('2d');
  // // 设置canvas大小
  // canvas.width = element.offsetHeight;
  // canvas.height = element.offsetWidth;
  // canvas.style.width = `${element.offsetHeight}px`;
  // canvas.style.height = `${element.offsetWidth}px`;
  // // 将元素绘制到canvas上
  // const data = (new XMLSerializer()).serializeToString(element);
  // const DOMURL = window.URL || window.webkitURL || window;
  // const img = new Image();
  // const svg = new Blob([data], { type: 'image/svg+xml;charset=utf-8' });
  // const url = DOMURL.createObjectURL(svg);

  // img.onload = function () {
  //   ctx.drawImage(img, 0, 0);
  //   DOMURL.revokeObjectURL(url);

  //   // 转换canvas为图片
  //   imageUrl.value = canvas.toDataURL('image/png');
  // };

  // img.src = url;
  // img.download = 'groupPhoto.png';
  // img.click();
}
async function OpenMaterailPop() {
  const res = await getAllCards({
    phone: userInfo.value.phone,
    size: 100,
  })
  if (res.code === 200) {
    materailState.source = res.data.records
    visible.value = true
  }
}
function closePop() {
  // materailState.source = null;
  visible.value = false
  saveImgVisible.value = false
}
function cancelActived() {
  materailState.activedId = ''
}
function setActived(id) {
  materailState.activedId = id
}
function toggleBg(op) {
  let newValue = backgroundState.current + op
  if (newValue > backgroundState.options.length) {
    newValue = 1
  }
  if (newValue < 1) {
    newValue = backgroundState.options.length
  }
  backgroundState.current = newValue
  backgroundState.eleStyle = {
    'background-image': `url( ${cardBaseUrl.value + backgroundState.options[backgroundState.current - 1]})`,
  }
  // backgroundState.eleStyle = {
  //   'background-image': `url( ${` ${backgroundState.options[0]}`})`,
  // }
  materailState.target = []
}
function deleteCard(id) {
  const index = materailState.target.findIndex((item) => {
    return item.id === id
  })
  console.log('deleteCard', materailState.target, id, index)
  materailState.target.splice(index, 1)
}
function addCard(card) {
  console.log('card', card)
  if (
    materailState.target.filter((item) => {
      return item.id === card.id
    }).length > 0
  ) {
    console.log('无法添加')
  }
  else {
    materailState.target.push(card)
  }
  closePop()
  addEvent()
}
function addEvent() {
  console.log('materailState.target', materailState.target)
  setTimeout(() => {
    for (let i = 0; i < materailState.target.length; i++) {
      const element = materailState.target[i]
      const stage = document.getElementById(`material_img_${element.id}`)
      const hammerExample = new Hammer(stage)
      let initScale = 1
      const state = {
        id: element.id,
        x: 0,
        y: 0,
        scale: 1,
        angle: 0,
      }

      const isMatch
        = materailState.hammerManages.filter((item) => {
          return item.key === element.id
        }).length > 0
      if (!isMatch) {
        materailState.hammerManages.push(state)
      }

      hammerExample.add(new Hammer.Rotate({ threshold: 0 })).recognizeWith(hammerExample.get('pan'))
      hammerExample.add(new Hammer.Pan({ direction: Hammer.DIRECTION_ALL, threshold: 0 }))
      hammerExample.add(new Hammer.Pinch({ threshold: 0 })).recognizeWith([hammerExample.get('pan'), hammerExample.get('rotate')])

      let START_X = 0
      let START_Y = 0
      const a = stage.style.transform || stage.style.mozTransform || stage.style.webkitTransform
      if (a.includes('translate') && !a.includes('scale') && !a.includes('rotate')) {
        console.log('a', a)
        START_X = Number(a.split('translate(')[1].split('px')[0])
        START_Y = Number(a.split('translate(')[1].split(')')[0].split(')')[0].split(',')[1].split('px')[0])
      }

      hammerExample.on('hammer.input', (e) => {
        // console.log("hammer.input", e);
        const a = stage.style.transform || stage.style.mozTransform || stage.style.webkitTransform
        const ex = a.includes('translate') && a.includes('scale') && a.includes('rotate')
        if (ex && e.isFinal) {
          START_X = Number(a.split('translate(')[1].split('px')[0])
          START_Y = Number(a.split('translate(')[1].split(')')[0].split(')')[0].split(',')[1].split('px')[0])
        }
      })

      // 旋转相关
      let preAngle = 0
      let tempAngleFlag = 0
      let deltaAngle = 0
      let startRotateAngle = 0
      let initAngle = 0
      hammerExample.on('rotatestart rotatemove rotateend', (e) => {
        console.log('rotatestart rotatemove rotateend', e)

        // const rotation = Math.round(e.rotation)
        // console.log('【hammerExample】', 'rotate', e)
        // state.angle = rotation
        // setTransform(element.id)
        if (e.type === 'rotatestart') {
          startRotateAngle = e.rotation
          tempAngleFlag = 0
        }
        if (e.type === 'rotatemove') {
          if (tempAngleFlag === 0) {
            preAngle = startRotateAngle
            tempAngleFlag++
          }
          else {
            deltaAngle = e.rotation - preAngle
            // transform.rz = 1;  //非0  垂直xy轴
            state.angle = initAngle + deltaAngle
            setTransform()
          }
        }
        // 旋转结束  记录当前图片角度
        if (e.type === 'rotateend') {
          initAngle = state.angle
        }
      })

      // 移动
      hammerExample.on('panmove', (e) => {
        console.log('【hammerExample】', 'e', e)
        console.log('【hammerExample】', 'Start', START_X, START_Y)
        // console.log('【hammerExample】', 'Panend', e.deltaX, e.deltaY)
        let tempX = START_X + e.deltaX
        let tempY = START_Y + e.deltaY
        const rangeEle = document.getElementById('target_item')
        const targetEleW = e.target.offsetWidth
        const targetEleH = e.target.offsetHeight
        const maxW = rangeEle.offsetWidth - targetEleW
        const maxH = rangeEle.offsetHeight - targetEleH
        console.log('【hammerExample】', 'targetEle', targetEleW, targetEleH)
        console.log('【hammerExample】', 'max', maxW, maxH)

        if (tempX < 0) {
          tempX = 0
        }
        if (tempY < 0) {
          tempY = 0
        }
        if (tempX > maxW) {
          tempX = maxW
        }
        if (tempY > maxH) {
          tempY = maxH
        }
        state.x = tempX
        state.y = tempY
        console.log('【hammerExample】', 'target', tempX, tempY)
        setTransform(element.id)
      })

      // 缩放
      hammerExample.on('pinchstart pinchmove', (e) => {
        if (e.type === 'pinchstart') {
          const a = stage.style.transform || stage.style.mozTransform || stage.style.webkitTransform
          const ex = a.includes('translate') && a.includes('scale') && a.includes('rotate')
          if (ex) {
            initScale = ex.split('scale(')[1].split(')')[0]
          }
          else {
            initScale = 1
          }
        }
        state.scale = initScale * e.scale
        setTransform()
      })

      function setTransform() {
        const t = state
        const value = `translate(${t.x}px,${t.y}px) scale(${t.scale}) rotate(${t.angle}deg)`
        stage.style.transform = value
        stage.style.transformStyle = value
        stage.style.webkitTransform = value /* 为Chrome/Safari */
        stage.style.mozTransform = value /* 为Firefox */
        stage.style.transform = value /* IE Opera? */
        // console.log("stage.style.transform", stage.style, value);
      }
    }
  }, 0)
}

/**
 * 禁止页面自带缩放
 */
function preventPinchZoom() {
  const touchStartHandler = (event) => {
    if (event.touches.length > 1) {
      event.preventDefault()
    }
  }

  const touchMoveHandler = (event) => {
    if (event.touches.length > 1) {
      event.preventDefault()
    }
  }

  document.addEventListener('touchstart', touchStartHandler, { passive: false })
  document.addEventListener('touchmove', touchMoveHandler, { passive: false })

  return () => {
    document.removeEventListener('touchstart', touchStartHandler)
    document.removeEventListener('touchmove', touchMoveHandler)
  }
}

// map event

async function getScene() {
  const res = await getSceneBg()
  if (res.code === 200) {
    // state.info = res.data.records
    backgroundState.options = res.data.records.map((i) => {
      return i.pic
    })
    console.log('backgroundState.options', backgroundState.options)

    backgroundState.eleStyle = {
      'background-image': `url( ${cardBaseUrl.value + backgroundState.options[0]})`,
    }

    // backgroundState.eleStyle = {
    //   'background-image': `url(http://101.132.182.107:2024/images/0.jpeg)`,
    // }

    // backgroundState.options = [
    //   'http://101.132.182.107:2024/images/1212.jpg',
    //   'https://jwc-static.jdwxk.com/imgs/activities/group_photo/2.png',
    // ]
    // backgroundState.eleStyle = {
    //   'background-image': `url( ${` ${backgroundState.options[0]}`})`,
    // }
  }
}

onMounted(() => {
  userStore.GetUserInfo()
  preventPinchZoom()
  getScene()
})
onUnmounted(() => {
  preventPinchZoom()
})
</script>

<style lang="less" scoped>
.group_photo {
  box-sizing: border-box;
  overflow: hidden;
  padding-bottom: 54px;
  position: relative;
  width: 100%;
  height: 100vh;
  background: #f5ead2;

  .navBar {
    position: fixed;
    width: 100vw;
  }

  .right_info {
    position: fixed;
    z-index: 101;
    right: 0;
    top: 0;
    width: 60px;
    height: 100vh;
    display: flex;
    padding-bottom: 50px;
    justify-content: flex-end;
    flex-direction: column;
    box-sizing: border-box;
  }

  .address {
    height: 40px;
    width: 80px;
    gap: 4px;
    right: 15px;
    margin-bottom: 103px;
    position: relative;
    width: 80px;
    right: 0;

    img {
      width: 12px;
      height: 14px;
    }
  }

  .user {
    // right: 20px;
    bottom: 20px;
    gap: 6px;
    margin-right: 28px;
    height: 40px;
    // width: 80px;
    position: relative;
    width: 160px;
    right: 40px;

    .avatar {
      width: 31.5px;
      height: 31.5px;
      background-color: #f7eed9;
      border-radius: 31.5px;
    }
  }

  .background_box {
    position: absolute;
    transform: translate(-50%, -50%);
    left: calc(50% - 10px);
    top: calc(50%);
    // height: 660px;
    height: 80vh;
    width: 318px;
    border-radius: 10.5px;
    background: #ebce95;
    display: flex;
    align-items: center;
    justify-content: center;

    .background_content {
      // height: 640px;
      height: calc(80vh - 20px);
      width: 298px;
      background: white;
    }
  }

  .decorations {
    background: #e4d1ae;
    transform: translate(-50%, -50%) rotate(6.2deg);
  }

  .main_view {
    .background_1 {
      background: url('https://jwc-static.jdwxk.com/imgs/activities/group_photo/1.png');
    }

    .background_2 {
      background: url('https://jwc-static.jdwxk.com/imgs/activities/group_photo/2.png');
    }

    .background_3 {
      background: url('https://jwc-static.jdwxk.com/imgs/activities/group_photo/3.png');
    }

    .background_content {
      background-size: cover;
      background-repeat: no-repeat;
    }
  }

  .hover_btns {
    position: absolute;
    left: calc(159px);
    // bottom: calc(-149px + 50vh - 330px - 15px);
    bottom: calc(-149px + 50vh - 40vh - 15px);
    height: 318px;
    width: 30px;
    padding: 40px 0;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .btn {
      border-right: 2px solid #fffbf3;
      border-bottom: 2px solid #fffbf3;
      border-top: 2px solid #fffbf3;
      border-radius: 0 8px 8px 0;
      width: 30px;
      height: 64px;

      img {
        width: 13px;
        height: 13px;
      }

      writing-mode: vertical-lr;
      font-size: 10px;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;
    }

    .btn1 {
      background: #c6746b;
    }

    .btn2 {
      background: #ceb2a5;
    }
  }

  .landscape {
    transform: rotate(90deg);
  }

  .materail_pop {
    color: #333333;
    top: 0;
    right: 0;
    height: 100vh;
    width: 100vw;

    .van-overlay {
      width: 100vw;
      height: 100vh;
      left: 0;
    }

    .van-popup {
      max-width: none;
      height: calc(60vw + 60px);
      background-color: transparent !important;
      overflow: visible;
    }

    .box {
      border-bottom: 27px solid white;
      border-left: 30px solid transparent;
      border-right: 30px solid transparent;
      transform: rotate(180deg);
      width: 52px;
      margin-top: -1px;
      margin-left: calc(25vh - 26px);
    }

    .materail_pop_box {
      box-sizing: border-box;
      height: 547px;
      width: 274px;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      position: relative;
      background: url('https://jwc-static.jdwxk.com/imgs/activities/cards_bg.png');
      background-size: contain;
      background-repeat: no-repeat;

      .title {
        position: absolute;
        right: -70px;
        top: calc(70px - 15px);

        img {
          width: 140px;
          height: 30px;
        }
      }

      .close {
        position: absolute;
        right: -5px;
        bottom: 0;
        width: 48px;
        height: 38px;

        img {
          width: 18px;
          height: 18px;
        }
      }

      .tip {
        position: absolute;
        left: calc(-50% + 50vw - 159px - 20px);
        bottom: 50%;
        // transform: translate() scale() rotate();
      }

      .cards {
        height: 497px;
        width: 196px;
        overflow-y: scroll;
        margin: -11px auto 0 auto;
        display: flex;
        flex-wrap: wrap;
        column-gap: 11.5px;
        row-gap: 15px;
        align-items: flex-start;
        padding: 15px 0;

        .card {
          display: flex;
          flex-wrap: nowrap;
          align-items: center;
          width: 77px;
          height: 90px;
        }

        .card_img {
          border-radius: 6px;
          border: 2.5px solid #d1af7d;
          height: 90px;
          width: 67.5px;
        }

        .card_title {
          flex-shrink: 0;
          margin-right: -38px;
          position: relative;

          img {
            width: 76.5px;
            height: 19px;
          }

          span {
            position: absolute;
            left: 50%;
            top: 0;
            width: 100%;
            text-align: center;
            color: white;
            transform: translateX(-50%);
            line-height: 20px;
            font-size: 10px !important;
          }
        }
      }
    }
  }

  #saveImgPop span {
    position: absolute;
    transform: rotate(90deg);
    text-wrap: nowrap;
    top: 100px;
    left: calc(200px - 139px + 10px);
    color: white;
    height: calc(50vw - 139px - 10px);
    line-height: calc(50vw - 139px - 10px);
    width: 200px;
    text-align: center;
    bottom: 50%;
  }

  .source_area {
    display: flex;
    flex-wrap: wrap;
    gap: 40px;
    flex-shrink: 0;
  }

  .scene_bg {
    // position: absolute;
    // left: 0;
    // top: 0;
    float: left;
    // height: 640px;
    height: calc(80vh - 20px);
    width: 298px;
  }

  .scene_bg img {
    // height: 640px;
    height: calc(80vh - 20px);
    width: 298px;
    object-fit: cover;
  }

  .target_area {
    border-radius: 2px;
    background: white;
    display: flex;
    flex-wrap: wrap;

    .target_item {
      // height: 640px;
      height: calc(80vh - 20px);
      width: 298px;
      position: relative;

      .material_img {
        position: absolute;
        left: 0;
        top: 0;
        display: inline-block;
      }

      img {
        width: 90px;
      }

      .close {
        width: 20px;
        height: 20px;
        position: absolute;
        right: -30px;
        bottom: -30px;
        z-index: 101;
      }

      .material_img_actived::after {
        content: '';
        position: absolute;
        z-index: 100;
        width: 100%;
        /* 设置宽度为父元素的100% */
        height: 100%;
        /* 设置高度为父元素的100% */
        border: 1px solid white;
        box-sizing: content-box;
        padding: 20px;
        left: -20px;
        top: -20px;
        display: block;
        /* 转换为块级元素 */
      }
    }
  }

  .toggle_bg {
    transform: rotate(90deg);
    position: absolute;
    top: 50%;

    img {
      width: 29px;
      height: 29px;
      z-index: 99;
      position: absolute;
    }

    .last_img {
      left: 0;
      top: -2px;
    }

    .next_img {
      right: 0;
      bottom: -2px;
    }

    display: flex;
    align-items: center;
    justify-content: center;
    width: 89px;

    .current {
      width: 57px;
      height: 25px;
      text-align: center;
      box-sizing: border-box;
      border: 2px solid #e4dcc6;
      background-color: #fdfae6;
      color: #b67565;
    }
  }
}
</style>

<style lang="less">
#saveImgPop div {
  position: absolute;
  transform: translate(-50%, -50%);
  left: calc(50% - 10px);
  top: calc(50%);
  // height: 660px;
  height: 80vh;
  width: 318px;
  background: #ebce95;
  border-radius: 10.5px;
  display: flex;
  align-items: center;
  justify-content: center;

  img {
    // height: 640px;
    height: calc(80vh - 20px);
    width: 298px;
    object-fit: cover;
  }
}

#saveImgPop div::after {
  content: '长按图片保存';
  border-radius: 4px;
  position: absolute;
  transform: rotate(90deg);
  background: #ebce95;
  padding: 4px 8px;
  color: #333;
  left: 0;
}
</style>
